package org.opens.netty.chatServer.server.handle;

import cn.hutool.core.collection.CollectionUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.opens.netty.chatServer.message.GroupChatRequestMessage;
import org.opens.netty.chatServer.message.GroupChatResponseMessage;
import org.opens.netty.chatServer.server.session.GroupSessionFactory;

import java.util.List;

@ChannelHandler.Sharable
public class GroupChatRequestMessageHandle extends SimpleChannelInboundHandler<GroupChatRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupChatRequestMessage msg) throws Exception {
        String groupName = msg.getGroupName();

        List<Channel> membersChannel = GroupSessionFactory.getGroupSession().getMembersChannel(groupName);
        if (CollectionUtil.isNotEmpty(membersChannel)) {
            for (Channel channel : membersChannel) {
                channel.writeAndFlush(new GroupChatResponseMessage(msg.getFrom(), msg.getContent()));
            }
        }
    }
}
